import { createElement, appendChild } from './dom.js'
import { getPathArea } from './path-area.js'

/**
 * 默认配置
 */
const defaultOptions = {
    overBgColor: 'rgba(255,0,0,0.1)', // 前景色
    bgcolor: 'rgba(190,191,185,1)', // 刮层颜色
    text: '中奖了',
    textColor:'rgba(0,0,0,1)',
    fontSize:30,
    valveRate:0.7,
    drawWidth:20,
    ok:function(){},
    erasingRemovesErasedObjects:false
};
/**
 * 刮刮卡 类
 */
export class SCRATCHCARD {
    constructor(elm, options) {
        // 合并配置
        this.config = Object.assign(defaultOptions, options)
        this.elm = elm
        this.init()
    }
    /**
     * 页面初始化
     */
    init() {
        let { width, height } = this.elm.getBoundingClientRect()
        this.elm.innerHTML = ''
        let canvas = createElement('canvas')
        canvas.width = width
        canvas.height = height
        canvas.id = Date.now()
        appendChild(this.elm, canvas)
        this.initCanvas(canvas)
    }
    /**
     * 
     * @param {*} canvas 
     */
    initCanvas(dom) {
        let id = dom.id
        let canvas = this.__canvas = new fabric.Canvas(id)
        canvas.setOverlayColor(this.config.overBgColor, undefined, { erasable: false })
        canvas.freeDrawingBrush = new fabric.EraserBrush(canvas)
        canvas.freeDrawingBrush.width = this.config.drawWidth
        canvas.isDrawingMode = true

        let text = new fabric.Textbox(this.config.text, {
            fontSize: this.config.fontSize,
            fill: this.config.textColor,
            erasable: false,
            hasControls: false
        })

        canvas.add(text)

        let rect = new fabric.Rect({
            top: 0,
            left: 0,
            width: dom.width,
            height: dom.height,
            fill: this.config.bgcolor,
            opacity: 1
        })

        canvas.add(rect)

        canvas.centerObject(text)
        // canvas.renderAll()
        this.listen(canvas)
    }

    /**
     * 
     * @param {*} canvas 
     */
    listen(canvas) {
        let _ = this
        let maxArea = canvas.width * canvas.height
        canvas.on("erasing:end", ({ targets, drawables }) => {
            try {
                let objects = targets[0].eraser._objects
                let areas = []
                objects.forEach(object => {
                    let pathArr = object.path
                    let pathStr = ''
                    pathArr.forEach(path => {
                        pathStr += path.join(' ')
                    })

                    pathStr += 'z'
                    let area = getPathArea(pathStr, 200);
                    areas.push({
                        area: area,
                        path: pathStr
                    })
                });

                let sum = 0
                areas.forEach(area => {
                    sum += (area.area || 0)
                });
                // 如果面积只和大于设置的阀值
                if (sum > maxArea * _.config.valveRate){
                    _.config.ok()
                    if (_.config.erasingRemovesErasedObjects) {
                        targets.forEach(obj => canvas.remove(obj))
                    }
                }
            } catch (error) {
                console.warn(error)
            }
           
        })
    }
}

/**
 * 
 * @param {*} elm 
 * @param {*} options 
 * @returns 
 */
export function create(elm, options) {
    return new SCRATCHCARD(elm, options)
}